package com.wl.servlet;

import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

@MultipartConfig  // 1.添加注解
@WebServlet("/upload")
public class UploadServlet extends HttpServlet {

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1.得到上传那部分
        Part part = req.getPart("abc");
        // 2.得到上传的文件名
        String fileName = part.getSubmittedFileName();

        System.out.println(fileName);
        // 3.要文件上传到发布后项目下的upload目录中，得到发布后的项目绝对路径
        String realPath = this.getServletContext().getRealPath("/upload");
        // 目录不存在则创建
        if (!Files.exists(Paths.get(realPath))){
            Files.createDirectories(Paths.get(realPath));
        }
        // 4.把上传的文件拷贝到发布后的位置
        Files.copy(part.getInputStream(), Paths.get(realPath,fileName),
                StandardCopyOption.REPLACE_EXISTING);
        System.out.println(realPath);
    }
}
